package cn.kgc.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ArrayList01 {
    public int getArrayListLength(ArrayList list) throws Exception {
        //获取Class对象
        Class c = Class.forName("java.util.ArrayList");
        //映射Class对象c所表示类(即Arraylist)的属性
        Field field = c.getDeclaredField("elementData");
        //设置访问状态表示为true
        field.setAccessible(true);
        //返回指定对象上此 Field 表示的字段的值
        Object[] object = (Object[]) field.get(list);
        return object.length;
    }

    public static void main(String[] args) throws Exception {
        ArrayList01 arrayList01 = new ArrayList01();
        ArrayList arrayList = new ArrayList();

        for (int i = 0; i < 100; i++) {
            int length = arrayList01.getArrayListLength(arrayList);
            System.out.println("length = " + length);
            arrayList.add(i);

        }
    }
}